package service;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.view.View;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Set;


//import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GcmIntentService extends IntentService {
    /**
     * String section
     */
    private int badge = 0;
    private int id = 0;
    private String ALERT = "";
    private String SOUND = "";

    private final String TAG_ALERT = "alert";
    private final String TAG_APS= "aps";
    private final String TAG_BADGE = "badge";
    private final String TAG_ID = "id";
    private final String TAG_SOUND = "sound";

    /**
     * GCM
     */
    public static final String KEY_RECEIVE_GCM_NOTIFICATION = "CS Notification";

    public static final int NOTIFICATION_ID = 1;
    public static final int notification = 2;

    private String NOTIFICATION = null;

    /**
     * The others section
     */
    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder builder;

//    public static NotificationItemOfGCM notificationItemOfGCM = null;

    public GcmIntentService() {
        super("GcmIntentService");
    }

    //
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM
             * will be extended in the future with new message types, just ignore
             * any message types you're not interested in, or that you don't
             * recognize.
             */
            if (GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
//                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals(messageType)) {
//                sendNotification("Deleted messages on server: " +
//                        extras.toString());
                // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals(messageType)) {

                if (extras.get(KEY_RECEIVE_GCM_NOTIFICATION) != null) {
                    NOTIFICATION = extras.get(KEY_RECEIVE_GCM_NOTIFICATION).toString();
//                sendNotification(NOTIFICATION);
                    Log.i("", "NOTIFICATION " + NOTIFICATION);
                    // Post notification of received message.
                    JSONObject json = new JSONObject();
                    Set<String> keys = extras.keySet();
                    for (String key : keys) {
                        try {
                            // json.put(key, bundle.get(key)); see edit below
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                                json.put(key, JSONObject.wrap(extras.get(key)));
                            Log.i("", "json notification" + json);
                        } catch (JSONException e) {
                            //Handle exception here
                        }
                    }
                }
//                // get badge from GCM
//                try {
//                    JSONObject mJoNotification = new JSONObject(NOTIFICATION);
//                    //get string from mJoNotification
//                    id = mJoNotification.getInt(TAG_ID);
//                    //get json object from mJoNotification
//                    JSONObject mJoAps = mJoNotification.getJSONObject(TAG_APS);
//                    //get string from mJoAps
//                    ALERT = mJoAps.getString(TAG_ALERT);
//                    badge = mJoAps.getInt(TAG_BADGE);
//                    SOUND = mJoAps.getString(TAG_SOUND);
//                    notificationItemOfGCM = new NotificationItemOfGCM(badge, id, ALERT, SOUND);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                // update UI and show badge number
//                if (notificationItemOfGCM != null) {
//                        // use runOnUiThread avoid bug: Only the original thread that created a view hierarchy can touch its views
//                    ((Activity)Cloudstringers.mContext).runOnUiThread( new Runnable() {
//                        @Override
//                        public void run() {
//                            Cloudstringers.mTvBadgeNumberInActionBar.setVisibility(View.VISIBLE);
//                            Cloudstringers.mTvBadgeNumberInActionBar.setText("+" + String.valueOf(notificationItemOfGCM.getBadge()));
//                        }
//                    });
//
//                }
//                sendNotification(ALERT);
            }
        }

        // Release the wake lock provided by the WakefulBroadcastReceiver.
        WakefulBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    // This is just one simple example of what you might choose to do with
    // a GCM message.
//    private void sendNotification(String msg) {
//        mNotificationManager = (NotificationManager)
//                this.getSystemService(Context.NOTIFICATION_SERVICE);
//
////        //check cloudstringer activity is open or close
////        //is opening
////        if (Cloudstringers.IS_IN_ACTIVITY_CLOUDSTRINGERS) {
////            /**
////             * Check the navigation bar was showing or not
////             */
////            if (!NotificationsNavigationDrawerFragment.mViewContainer.isShown()) {
////                NotificationsNavigationDrawerFragment.mDrawerLayout
////                        .openDrawer(NotificationsNavigationDrawerFragment.mViewContainer);
////            } else {
////                NotificationsNavigationDrawerFragment.mDrawerLayout
////                        .closeDrawer(NotificationsNavigationDrawerFragment.mViewContainer);
////            }
////            // hide tv badge number
////            Cloudstringers.mTvBadgeNumberInActionBar.setText("");
////            Cloudstringers.mTvBadgeNumberInActionBar.setVisibility(View.GONE);
////            // is closing and not run background
////            Log.i("","getPackageName() " + getPackageName());
////        } else if (!Cloudstringers.IS_IN_ACTIVITY_CLOUDSTRINGERS && !isForeground(getPackageName())) {
////
////            //is closing and run background
////        } else if (!Cloudstringers.IS_IN_ACTIVITY_CLOUDSTRINGERS && isForeground(getPackageName())) {
////
////        }
//        // public static boolean = true
//        // onStart() -> onStop() boolean = false
//        // if boolean = false -> tat current app, new app
//        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
//                new Intent(this, Cloudstringers.class).putExtra("package.notification", 123).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK),
//                PendingIntent.FLAG_CANCEL_CURRENT);
//        NotificationCompat.Builder mBuilder =
//                new NotificationCompat.Builder(this)
//                        .setSmallIcon(R.drawable.ic_launcher).setContentTitle("");
//        // Set Big View style to see full content of the message
//        NotificationCompat.BigTextStyle inboxStyle =
//                new NotificationCompat.BigTextStyle();
//        inboxStyle.setBuilder(mBuilder);
//        inboxStyle.bigText("");
//        inboxStyle.setBigContentTitle("");
//        inboxStyle.setSummaryText("");
//        // Moves the big view style object into the notification object.
//        mBuilder.setStyle(inboxStyle);
//        mBuilder.setContentText(msg);
//        mBuilder.setDefaults(Notification.DEFAULT_ALL);
//        mBuilder.setContentIntent(contentIntent);
//        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
//
////        Notification.InboxStyle inboxstyle = new Notification.InboxStyle();
////    	String [] events = new String[1];
////    	events[0] = new String (msg);
////    	for(int i=0; i<events.length;i++ ){
////    		inboxstyle.addLine(events[i]);
////    	}
////
////    	NotificationManager notifimng = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
////    	Intent intent = new Intent (this, Cloudstringers.class);
////    	PendingIntent pintent = PendingIntent.getActivity(this, 0, intent, 0);
////    	Notification notifi = new Notification.Builder(this)
////    		.setContentTitle("Notification")
////    		.setSmallIcon(R.drawable.ic_launcher)
////    		.setContentIntent(pintent)
////    		.setStyle(inboxstyle)
////    		//.setStyle(new Notification.BigTextStyle().bigText(msg))
////    		.build();
////    	notifimng.notify(0, notifi);
//
//        /*Intent intent = new Intent(this, Home.class);
//    	PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
//
//    	// build notification
//    	// the addAction re-use the same intent to keep the example short
//    	Notification n  = new Notification.Builder(this)
//    	        .setContentTitle("New mail from " + "test@gmail.com")
//    	        .setContentText(msg)
//    	        .setSmallIcon(R.drawable.ic_launcher)
//    	        .setContentIntent(pIntent)
//    	        .setStyle(new Notification.BigTextStyle().bigText(msg))
//    	        .build();
//    	NotificationManager notificationManager =
//    	  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//
//    	notificationManager.notify(NOTIFICATION_ID, n); */
//    }

    public boolean isForeground(String myPackage){
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List< ActivityManager.RunningTaskInfo > runningTaskInfo = am.getRunningTasks(1);

        ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
        Log.i("", "componentInfo.getPackageName() " + componentInfo.getPackageName());
        if(componentInfo.getPackageName().equals(myPackage)) return true;
        return false;
    }
}